/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cn.bingoogolapple.badgeview.demo.slice;

import cn.bingoogolapple.badgeview.BGABadgeable;
import cn.bingoogolapple.badgeview.BGADragDismissDelegate;
import cn.bingoogolapple.badgeview.BgaBadgeTool;
import cn.bingoogolapple.badgeview.LogUtil;
import cn.bingoogolapple.badgeview.demo.model.MessageModel;
import cn.bingoogolapple.badgeview.demo.util.PixelMapFactoryUtil;
import cn.bingoogolapple.badgeview.demo.widget.BgaBadgeFloatingActionButton;
import cn.bingoogolapple.badgeview.demo.widget.BgaBadgeFrameLayout;
import cn.bingoogolapple.badgeview.demo.widget.BgaBadgeLinearLayout;
import cn.bingoogolapple.badgeview.demo.widget.BgaBadgeRadioButton;
import cn.bingoogolapple.badgeview.demo.widget.BgaBadgeView;
import cn.bingoogolapple.badgeview.demo.ResourceTable;
import cn.bingoogolapple.badgeview.demo.widget.BgaBadgeTextView;
import cn.bingoogolapple.badgeview.demo.widget.BgaBadgeImageView;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.Text;
import ohos.agp.utils.Color;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.ToastDialog;
import ohos.app.Context;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.eventhandler.InnerEvent;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;

import java.util.ArrayList;
import java.util.List;

/**
 * MainAbilitySlice
 *
 * @since 2021-04-21
 */
public class MainAbilitySlice extends AbilitySlice {
    private BgaBadgeTextView mTestBtv;
    private BgaBadgeImageView mNormalBiv;
    private BgaBadgeImageView mRoundedBiv;
    private BgaBadgeImageView mCircleBiv;
    private BgaBadgeLinearLayout mTestBrl;
    private BgaBadgeLinearLayout mTestBll;
    private BgaBadgeFloatingActionButton mChatBfab;
    private BgaBadgeView mTestBv;
    private BgaBadgeFrameLayout mTestBfl;
    private DirectionalLayout listContainer;

    private BgaBadgeRadioButton mHomeBrb;
    private BgaBadgeRadioButton mMessageBrb;
    private BgaBadgeRadioButton mDiscoverBrb;
    private BgaBadgeRadioButton mMeBrb;
    private PixelMap mPixelMap = null;

    // 顶层View
    private Component topComponent;
    private List<BGABadgeable> componentList = null;

    private final int badgeTextSizeSp = 15;
    private final int badgePaddingDpOne = 8;
    private final int badgePaddingDpTwo = 7;
    private final int badgeBorderWidthDp = 2;
    private final int cornerRadius50 = 50;
    private final int cornerRadius100 = 100;
    private final int delayTime500 = 500;
    private final int delayTime800 = 800;
    private final int delayTime1200 = 1200;

    /**
     * onStart
     *
     * @param intent
     */
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        componentList = new ArrayList<>();
        initFindByIdView();
        initViewOption();
        testRadioButton();
        mChatBfab.showTextBadge("8");
        mChatBfab.setDragDismissDelegate(new BGADragDismissDelegate() {
            @Override
            public void onDismiss(BGABadgeable badgeable) {
                new ToastDialog(MainAbilitySlice.this)
                        .setText("清空聊天消息")
                        .setAlignment(LayoutAlignment.TOP)
                        .show();
            }
        });

        // 注册mChatBfab
        componentList.add(mChatBfab);
    }

    private void initFindByIdView() {
        mTestBtv = (BgaBadgeTextView) findComponentById(ResourceTable.Id_btv_main_test);
        mTestBll = (BgaBadgeLinearLayout) findComponentById(ResourceTable.Id_bll_main_test);
        mNormalBiv = (BgaBadgeImageView) findComponentById(ResourceTable.Id_biv_main_normal);
        mRoundedBiv = (BgaBadgeImageView) findComponentById(ResourceTable.Id_biv_main_rounded);
        mCircleBiv = (BgaBadgeImageView) findComponentById(ResourceTable.Id_biv_main_circle);
        mTestBrl = (BgaBadgeLinearLayout) findComponentById(ResourceTable.Id_brl_main_test);
        mChatBfab = (BgaBadgeFloatingActionButton) findComponentById(ResourceTable.Id_bfab_main_chat);
        mTestBv = (BgaBadgeView) findComponentById(ResourceTable.Id_bv_main_test);
        mTestBfl = (BgaBadgeFrameLayout) findComponentById(ResourceTable.Id_bfl_main_test);
        listContainer = (DirectionalLayout) findComponentById(ResourceTable.Id_list_container);
        mHomeBrb = (BgaBadgeRadioButton) findComponentById(ResourceTable.Id_brb_main_home);
        mMessageBrb = (BgaBadgeRadioButton) findComponentById(ResourceTable.Id_brb_main_message);
        mDiscoverBrb = (BgaBadgeRadioButton) findComponentById(ResourceTable.Id_brb_main_discover);
        mMeBrb = (BgaBadgeRadioButton) findComponentById(ResourceTable.Id_brb_main_me);
        topComponent = findComponentById(ResourceTable.Id_stack_layout);
    }

    private void initViewOption() {
        mTestBv.showTextBadge("9");
        mTestBv.getBadgeViewHelper().setBadgeTextSizeSp(badgeTextSizeSp);
        mTestBv.getBadgeViewHelper().setBadgePaddingDp(badgePaddingDpOne);
        mTestBv.getBadgeViewHelper().setBadgeTextColorInt(Color.getIntColor("#FF0000"));
        mTestBv.getBadgeViewHelper().setBadgeBgColorInt(Color.getIntColor("#00FF00"));
        mTestBv.getBadgeViewHelper().setDraggable(true);
        mTestBv.getBadgeViewHelper().setBadgePaddingDp(badgePaddingDpTwo);
        mTestBv.getBadgeViewHelper().setBadgeBorderWidthDp(badgeBorderWidthDp);
        mTestBv.getBadgeViewHelper().setBadgeBorderColorInt(Color.getIntColor("#0000FF"));
        mTestBtv.showCirclePointBadge();

        // 注册mTestBtv
        componentList.add(mTestBtv);

        // 图像徽章1
        mNormalBiv.setPixelMap(ResourceTable.Media_icon_cat);
        mNormalBiv.showCirclePointBadge();

        // 图像徽章2
        ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions();
        mPixelMap = PixelMapFactoryUtil
                .getPixelMapFromResource(
                        this,
                        ResourceTable.Media_avatar_vip,
                        decodingOptions);
        mRoundedBiv.setPixelMap(ResourceTable.Media_icon_cat);
        mRoundedBiv.setCornerRadius(cornerRadius50);

        // 注册mRoundedBiv
        componentList.add(mRoundedBiv);

        // 添加徽章
        mRoundedBiv.showDrawableBadge(mPixelMap);

        // 图像徽章三
        mCircleBiv.setPixelMap(ResourceTable.Media_icon_cat);
        mCircleBiv.setCornerRadius(cornerRadius100);
        mCircleBiv.showDrawableBadge(mPixelMap);
        componentList.add(mCircleBiv);

        mTestBll.showDrawableBadge(mPixelMap);

        // 注册mTestBll
        componentList.add(mTestBll);

        // 布局徽章
        mTestBrl.showTextBadge("LoveOHOS");

        // 注册mTestBrl
        componentList.add(mTestBrl);

        mTestBfl.showTextBadge("8");
        EventRunner runnerA = EventRunner.create("downloadRunner");

        // 3.创建MyEventHandler实例
        MyEventHandler handler1 = new MyEventHandler(runnerA, this);

        // 4.向线程A发送事件
        handler1.sendEvent(MyEventHandler.CODE_DOWNLOAD_FILE1, delayTime500);
        MyEventHandler handler2 = new MyEventHandler(runnerA, this);

        // 4.向线程A发送事件
        handler2.sendEvent(MyEventHandler.CODE_DOWNLOAD_FILE2, delayTime800);
        MyEventHandler handler3 = new MyEventHandler(runnerA, this);

        // 4.向线程A发送事件
        handler3.sendEvent(MyEventHandler.CODE_DOWNLOAD_FILE3, delayTime1200);
        initListContainer();
    }

    private void testRadioButton() {
        mHomeBrb.showTextBadge("1");
        mHomeBrb.setDragDismissDelegate(new BGADragDismissDelegate() {
            @Override
            public void onDismiss(BGABadgeable badgeable) {
                new ToastDialog(MainAbilitySlice.this)
                        .setText("消息单选按钮徽章拖拽消失")
                        .setAlignment(LayoutAlignment.TOP)
                        .show();
            }
        });

        // 注册mHomeBrb
        componentList.add(mHomeBrb);

        mMessageBrb.showTextBadge("1");
        mDiscoverBrb.showTextBadge("...");

        // 图像徽章2
        ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions();
        PixelMap pixelMap = PixelMapFactoryUtil.
                getPixelMapFromResource(this, ResourceTable.Media_avatar_vip, decodingOptions);

        // 添加徽章
        mMeBrb.showDrawableBadge(pixelMap);
    }

    /**
     * onActive
     */
    @Override
    public void onActive() {
        super.onActive();
        LogUtil.error(MainAbilitySlice.class.getName(), "onActive");
    }

    /**
     * onForeground
     *
     * @param intent
     */
    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    private void initListContainer() {
        List<MessageModel> modelList = MessageModel.getTestData();
        for (int index = 0; index < modelList.size(); index++) {
            BgaBadgeLinearLayout layout = (BgaBadgeLinearLayout) LayoutScatter.getInstance(this)
                    .parse(ResourceTable.Layout_item_message, null, false);
            BgaBadgeLinearLayout itemView = (BgaBadgeLinearLayout) layout.
                    findComponentById(ResourceTable.Id_bv_item_test);
            itemView.showTextBadge(modelList.get(index).getNewMsgCount() + "");
            Text tvItemMessageTitle = (Text) layout.findComponentById(ResourceTable.Id_tv_item_message_title);
            tvItemMessageTitle.setText(modelList.get(index).getTitle());
            Text tvItemMessageDetail = (Text) layout.findComponentById(ResourceTable.Id_tv_item_message_detail);
            tvItemMessageDetail.setText(modelList.get(index).getDetail());

            int finalIndex = index;
            itemView.setDragDismissDelegate(new BGADragDismissDelegate() {
                @Override
                public void onDismiss(BGABadgeable badgeable) {
                    new ToastDialog(MainAbilitySlice.this)
                            .setText(modelList.get(finalIndex).getTitle() + "的徽章消失")
                            .setAlignment(LayoutAlignment.TOP)
                            .show();
                }
            });

            itemView.setClickedListener(new Component.ClickedListener() {
                @Override
                public void onClick(Component component) {
                    new ToastDialog(MainAbilitySlice.this)
                            .setText("点击条目" + modelList.get(finalIndex).getTitle())
                            .setAlignment(LayoutAlignment.TOP)
                            .show();
                }
            });

            // 注册itemView
            componentList.add(itemView);
            listContainer.addComponent(layout);
        }

        // 统一传递当前的View和注册需要添加徽章的自定义View
        BgaBadgeTool.initBgaBadgeDrawView(topComponent, componentList);
    }

    /**
     * MyEventHandler
     *
     * @since 2021-04-21
     */
    public class MyEventHandler extends EventHandler {
        /**
         * Image1
         */
        public static final int CODE_DOWNLOAD_FILE1 = 1;
        /**
         * Image2
         */
        public static final int CODE_DOWNLOAD_FILE2 = 2;
        /**
         * Image3
         */
        public static final int CODE_DOWNLOAD_FILE3 = 3;

        private Context mContext;

        /**
         * MyEventHandler
         *
         * @param runner
         * @param context
         * @throws IllegalArgumentException
         */
        public MyEventHandler(EventRunner runner, Context context) throws IllegalArgumentException {
            super(runner);
            this.mContext = context;
        }

        /**
         * processEvent
         *
         * @param event
         */
        @Override
        public void processEvent(InnerEvent event) {
            super.processEvent(event);
            if (event == null) {
                return;
            }

            int eventId = event.eventId;
            switch (eventId) {
                case CODE_DOWNLOAD_FILE1: {
                    mContext.getUITaskDispatcher().asyncDispatch(() -> {
                        // 更新UI的操作
                        mRoundedBiv.hiddenBadge();
                    });
                    break;
                }
                case CODE_DOWNLOAD_FILE2: {
                    mContext.getUITaskDispatcher().asyncDispatch(() -> {
                        // 更新UI的操作
                        mRoundedBiv.showCirclePointBadge();
                    });
                    break;
                }
                case CODE_DOWNLOAD_FILE3: {
                    mContext.getUITaskDispatcher().asyncDispatch(() -> {
                        // 更新UI的操作
                        ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions();
                        PixelMap pixelMap = PixelMapFactoryUtil.
                                getPixelMapFromResource(mContext, ResourceTable.Media_avatar_vip, decodingOptions);
                        mRoundedBiv.showDrawableBadge(pixelMap);
                    });
                    break;
                }
                default:
                    break;
            }
        }
    }
}
